package org.llc.user.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.llc.common.model.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.llc.user.enums.UserOauthServiceCode;

import javax.annotation.Resource;

/**
 * UserAccountController
 *
 * @author llc
 * @date 2020/5/15 17:27
 * @since 1.0.0
 */
@Api(tags = {"app: 用户账户相关","检查是否授权"} )
@Slf4j
@RestController
@RequestMapping("/app/v1/user")
public class UserAccountController {

    /**
     * tokenStore
     */
    @Resource
    private TokenStore tokenStore;

    /**
     * 用户登出
     * 登出移除access_token和refresh_token
     * @return org.llc.common.model.Result
     * @author llc
     * @date 2020/5/15 17:25
     */
    @ApiOperation(value = "用户登出")
    @PostMapping(value = "/logout")
    public Result removeToken() {

        // 拿到当前用户信息
        Authentication user = SecurityContextHolder.getContext().getAuthentication();
        // 令牌
        String accessTokenValue = null;
        if (user != null) {
            if (user instanceof OAuth2Authentication) {
                OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) user.getDetails();
                accessTokenValue = details.getTokenValue();
            }
        }
        // 未知异常
        if(null == accessTokenValue){
            return Result.failed(UserOauthServiceCode.UNKNOWN_LOGOUT_ERR.getCode(),UserOauthServiceCode.UNKNOWN_LOGOUT_ERR.getMsg());
        }
        //确认token存在
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
        if (accessToken != null) {
            // 移除access_token
            tokenStore.removeAccessToken(accessToken);

            // 移除refresh_token
            if (accessToken.getRefreshToken() != null) {
                tokenStore.removeRefreshToken(accessToken.getRefreshToken());
            }

        }
        log.info("用户登出");
        return Result.succeed();
    }
}
